/**
 * 来自农场管家地图拾取坐标操作
 * @author 415214115@qq.com
 * @time 2024-9-5 11:22:15
 */

import mars from "@/config/mars3d";
import { graphicLayer } from "@/utils/initMap";
import { useStore } from "@/stores/index1";
const store = useStore();
interface Query {
    from?: string;
    teamName?: string;
    addr?: string;
    origin?: string;
    lng?: string;
    lat?: string;
    editor?: any;
}

export const loadFon = () => {
    const query: Query = getUrlParam();
    // console.log(query)
    // 判断是否来自农场管家
    if (query && query.from == "farmboss") {
        // 关闭图层控件
        store.tool.topBtn.coverage = false;
        // 关闭搜索控件
        store.tool.topBtn.search = false;
        // 关闭工具控件
        store.tool.topBtn.tool = false;
        // 打开标记控件
        console.log(query.editor, "query.editor");
        if (query.editor == "true") {
            store.tool.topBtn.sign = true;
        }
    } else {
        // 关闭图层控件
        store.tool.topBtn.coverage = true;
        // 关闭搜索控件
        store.tool.topBtn.search = true;
        // 关闭工具控件
        store.tool.topBtn.tool = true;
        store.tool.topBtn.sign = false;
    }
    if (query.lng && query.lat) {
        if (query.lng != "null" && query.lat != "null") {
            // 判断是否存在坐标
            renderer(query.lng, query.lat);
        }
    }
};
// 添加标记
export const signMaps = () => {
    const query: Query = getUrlParam();
    graphicLayer.startDraw({
        type: "billboard",
        // attr:{
        from: query.from,
        // },
        style: {
            image: "http://mars3d.cn/img/marker/mark-blue.png", // 用于矢量对象的 图像、URI或Canvas
            scale: 1, // 图像大小的比例
            rotationDegree: 0, // 旋转角度（度数值，0-360度），与rotation二选一
            scaleByDistance: false, // 是否按视距缩放 或 设定基于与相机的距离设置比例。
            scaleByDistance_far: 1000000, // 上限
            scaleByDistance_farValue: 0.1, // 上限比例值
            scaleByDistance_near: 1000, // 下限
            scaleByDistance_nearValue: 1, // 下限比例值
            distanceDisplayCondition: false, // 是否按视距显示 或 指定此框将显示在与摄像机的多大距离。
            distanceDisplayCondition_far: 100000, // 最大距离
            distanceDisplayCondition_near: 0, // 最小距离
            visibleDepth: false, // 是否被遮挡
            clampToGround: true, // 是否贴地
            isLabel: false, // 是否文字
        },
    });
    graphicLayer.bindPopup(function (event: any) {
        const attr = event.graphic.attr || {};
        attr["地址"] = UrlDecode(query.addr);
        attr["经度"] = event.graphic.points[0].lng;
        attr["纬度"] = event.graphic.points[0].lat;
        // attr["海拔"] = event.graphic.points[0].alt
        attr["备注"] = "";

        return mars.mars3d.Util.getTemplateHtml({
            title: UrlDecode(query.teamName),
            template: "all",
            attr,
        });
    });
    monitor();
};

// 有坐标时渲染标记
const renderer = (lng: any, lat: any) => {
    const query: any = getUrlParam();
    const graphic: any = new mars.mars3d.graphic.BillboardEntity({
        position: [lng, lat],
        // attr:{
        //     from: query.from,
        // },
        from: query.from,
        style: {
            image: "http://mars3d.cn/img/marker/mark-blue.png", // 用于矢量对象的 图像、URI或Canvas
            scale: 1, // 图像大小的比例
            rotationDegree: 0, // 旋转角度（度数值，0-360度），与rotation二选一
            scaleByDistance: false, // 是否按视距缩放 或 设定基于与相机的距离设置比例。
            scaleByDistance_far: 1000000, // 上限
            scaleByDistance_farValue: 0.1, // 上限比例值
            scaleByDistance_near: 1000, // 下限
            scaleByDistance_nearValue: 1, // 下限比例值
            distanceDisplayCondition: false, // 是否按视距显示 或 指定此框将显示在与摄像机的多大距离。
            distanceDisplayCondition_far: 100000, // 最大距离
            distanceDisplayCondition_near: 0, // 最小距离
            visibleDepth: false, // 是否被遮挡
            clampToGround: true, // 是否贴地
            isLabel: false, // 是否文字
        },
        flyTo: true,
    } as any);
    graphicLayer.bindPopup(function (event: any) {
        const attr = event.graphic.attr || {};
        attr["地址"] = UrlDecode(query.addr);
        attr["经度"] = event.graphic.points[0].lng;
        attr["纬度"] = event.graphic.points[0].lat;
        attr["备注"] = "";

        return mars.mars3d.Util.getTemplateHtml({
            title: UrlDecode(query.teamName),
            template: "all",
            attr,
        });
    });
    setTimeout(() => {
        //    window.onload = () => {
        graphicLayer.addGraphic(graphic);
        if (query.editor == true) {
            graphic.startEditing();
            monitor();
        }

        //    }
    }, 300);
    //
};
// 监听绘制完成
const monitor = () => {
    const query: any = getUrlParam();
    graphicLayer
        .on(mars.mars3d.EventType.drawCreated, (e: any) => {
            let objData = e.graphic;
            objData.startEditing();
            setTimeout(() => {
                // console.log('准备发送消息')
                window.parent.postMessage({ location: objData.points[0] }, query.origin);
            }, 300);
        })
        .on(mars.mars3d.EventType.editMovePoint, function (e: any) {
            // 修改
            let objData = e.graphic;
            setTimeout(() => {
                // console.log('准备发送消息')
                window.parent.postMessage({ location: objData.points[0] }, query.origin);
            }, 300);
        });
};
// 获取到url参数
const getUrlParam = () => {
    let url: string = window.location.href;
    const Params = {};
    if (url.indexOf("?") > 0) {
        //判断是否有qurey
        let parmas = url.slice(url.indexOf("?") + 1); //截取出query
        const paramlists = parmas.split("&"); //分割键值对
        for (const param of paramlists) {
            let a = param.split("=");
            Object.assign(Params, { [a[0]]: a[1] }); //将键值对封装成对象
        }
    }
    return Params;
};
// url文字解码
const UrlDecode = (text: any) => {
    var uzipStr = "";
    for (var i = 0; i < text.length; i += 1) {
        var chr = text.charAt(i);
        if (chr === "+") {
            uzipStr += " ";
        } else if (chr === "%") {
            var asc = text.substring(i + 1, i + 3);
            if (parseInt("0x" + asc) > 0x7f) {
                uzipStr += decodeURI("%" + asc.toString() + text.substring(i + 3, i + 9).toString());
                i += 8;
            } else {
                uzipStr += AsciiToString(parseInt("0x" + asc));
                i += 2;
            }
        } else {
            uzipStr += chr;
        }
    }

    return uzipStr;
};
const AsciiToString = (asccode: any) => {
    return String.fromCharCode(asccode);
};
